package com.community.common.controller;


import com.alibaba.fastjson.JSONObject;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.constant.CameraSnConstant;
import com.community.common.pojo.domain.Camera;
import com.community.common.pojo.dto.CameraCondition;
import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.LayuiPage;
import com.community.common.pojo.response.MyResponse;
import com.community.common.service.CameraService;
import com.community.common.service.ManagerUserService;
import com.community.common.service.PublicUserService;
import com.community.common.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 相机表 前端控制器
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@Slf4j
@Controller
@RequestMapping("/camera")
public class CameraController {

    @Resource
    private CameraService cameraService;
    @Resource
    private ManagerUserService managerUserService;
    @Autowired
    private PublicUserService publicUserService;

    @ResponseBody
    @PostMapping("/add")
    public MyResponse add(Camera camera) {
        return cameraService.add(camera);
    }

    @ResponseBody
    @PostMapping("/delete")
    public MyResponse delete(@RequestBody List<Long> ids) {
        boolean delete = cameraService.delete(ids);
        if (delete) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    @ResponseBody
    @PostMapping("/edit")
    public MyResponse edit(Camera camera) {
        boolean edit = cameraService.edit(camera);
        if (edit) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    @GetMapping("editPage")
    public String editPage(Long id, ModelMap map) {
        Camera camera = cameraService.getById(id);
        map.put("camera", camera);
        return "manage/camera_edit";
    }

    @ResponseBody
    @PostMapping("/queryByPage")
    public LayuiPage queryByPage(@RequestBody PageRequest<CameraCondition> cameraConditionPageRequest, HttpSession session) {
        List<Camera> communityList = cameraService.queryByPage(cameraConditionPageRequest,
                managerUserService.getCommunityIdFromSession(session));
        return LayuiPage.parsePage(communityList);
    }

    @ResponseBody
    @PostMapping("/openDoorByCamera")
    public MyResponse openDoorByCamera(@RequestBody CameraCondition condition) {
        log.info("=========================" + JSONObject.toJSONString(condition) + "===================");
        if (StringUtils.isEmpty(condition.getSn()) || StringUtils.isEmpty(condition.getOpenId())) {
            return MyResponse.fail(CodeEnum.PARAMETER_EXCEPTION);
        }
        if (cameraService.checkSn(condition.getSn())) {
            return MyResponse.fail(CodeEnum.NOT_FOUND, "sn 不存在");
        }
        if (!publicUserService.whetherOwner(condition.getOpenId())) {
            return MyResponse.fail(CodeEnum.SYSTEM_NO_LOGIN, "用户不是业主 无权操作开门");
        }
        log.info("condition.getSn()=====================" + condition.getSn() + "==========================");
        CameraSnConstant.snMap.put(condition.getSn(), condition.getSn());
        log.info("=====snMap=====" + JSONObject.toJSONString(CameraSnConstant.snMap) + "===========================");
        return MyResponse.success();
    }

    @ResponseBody
    @PostMapping("/createQRCode")
    public MyResponse createQRCode(@RequestBody String sn) {
        Camera bySn = cameraService.getBySn(sn);
        boolean qrCode = cameraService.createQRCode(sn, bySn);

        if (qrCode) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }


    @ResponseBody
    @PostMapping("/queryIsSuccess")
    public MyResponse queryIsSuccess(@RequestBody String body) {
        CacheUtil.OpenDoorElement openDoorElement = null;
        String sn = null;
        try {
            sn = JSONObject.parseObject(body).getString("sn");
            openDoorElement = (CacheUtil.OpenDoorElement) CacheUtil.cache.get(sn);
        } catch (Exception e) {
            log.info("======openDoorElement======error", e);
        }

        if (openDoorElement == null) {
            return MyResponse.fail("请等待，尚未查询到开门信息");
        }

        if (CacheUtil.OpenDoorEnum.SUCCESS.name().equals(openDoorElement.getStatus())) {
            CacheUtil.cache.invalidate(sn);
            return MyResponse.success("已开门");
        }
        return MyResponse.fail("开门失败：" + openDoorElement.getMsg());
    }

}
